package com.exchange.task;

import com.exchange.common.model.OtcAdvert;
import com.exchange.common.model.OtcOrder;
import com.exchange.common.model.UserWallet;
import com.exchange.constant.BizConst;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import cn.hutool.core.util.NumberUtil;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


public class AutoCancelOtcTask {

    /**
     * 自动取消OTC超时订单
     */
    public void autoCancel() throws Exception {
        //获取当前时间十五分钟前的数据
        Date dateBefore15Min = new Date(System.currentTimeMillis() - 15*60*1000);       
        List<OtcOrder> otcOrders = OtcOrder.dao.find("SELECT * FROM t_otc_order WHERE state = 1 AND createTime < ?", dateBefore15Min);
        //遍历，自动取消
        for(int idx = 0; idx < otcOrders.size(); idx ++){
            //取消
            cancelOtcOrder(otcOrders.get( idx));
        }
    }
    
    @Before(Tx.class)
    public void cancelOtcOrder(OtcOrder otcOrder) {
    	Date date = new Date();
        //买单退单
        if (!otcOrder.getType()) {
        	//恢复广告数量
        	OtcAdvert otcAdvert = OtcAdvert.dao.findById(otcOrder.getAdvertId());
        	otcAdvert.setSurplus(NumberUtil.add(otcAdvert.getSurplus(), otcOrder.getNum()));
        	otcAdvert.setVersion(otcAdvert.getVersion() + 1).setUpdateTime(date).update();
        } else {
    		BigDecimal znum = NumberUtil.add(otcOrder.getNum(), otcOrder.getFeeRate());
        	//解冻钱包
    		UserWallet userWallet = UserWallet.dao.findFirst("SELECT * FROM t_user_wallet WHERE userId = ? AND coin = ? ", otcOrder.getUserId(), otcOrder.getCoin());
    		userWallet.setBalanceOTC(NumberUtil.add(userWallet.getBalanceOTC(), znum))
			.setFrozenOTC(NumberUtil.sub(userWallet.getFrozenOTC(), znum)).setVersion(userWallet.getVersion() + 1)
			.setUpdateTime(date).update();
        }
        otcOrder.setState(BizConst.OtcOrder.cancel).setUpdateTime(date).setVersion(otcOrder.getVersion() + 1).update();
    }


}
